﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using IGM.DataProvider;
using IGM.Framework.Commons;
using IGM.Framework.Constants;

namespace IGM.Presentation.Management
{
    public partial class StudentsControl : UserControl
    {
        private readonly Business.Business _business;

        public StudentsControl()
        {
            InitializeComponent();

            _business = Main.Main.Instance.IgmBusiness;
        }

        private void StudentsControlLoad(object sender, EventArgs e)
        {
            LoadMajor();
            LoadStudent();
            Dock = DockStyle.Top;
        }

        #region -- Student --

        private void LoadMajor()
        {
            cboMajors.DataSource = _business.GetListMajor();
            cboMajors.DisplayMember = PropertiesConstants.Name;
            cboMajors.ValueMember = PropertiesConstants.Id;
        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadStudent()
        {
            dgvStudents.DataSource = _business.GetListStudentByMajorId(((Major) cboMajors.SelectedItem).Id);
            DataGridViewHelper.ShowHideColumns(dgvStudents,
                                               new[] { PropertiesConstants.IsChecked, PropertiesConstants.Name, "Code", "DateOfBirth", "Term" });
            DataGridViewHelper.ShowIsCheck(dgvStudents);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvStudents, false);
            DataGridViewHelper.ChangeDgvHeaderText(dgvStudents, new[] { "IsChecked", "Code", "Name", "DateOfBirth", "Term" },
                                                   new[] { "Chọn", "Mã sinh viên", "Họ và tên", "Ngày tháng năm sinh", "Sinh viên năm cuối"});

            StudentCurrentRowChanged();
        }

        private void StudentCurrentRowChanged()
        {
            if (dgvStudents.CurrentRow != null)
            {
                txtStudentName.Text = dgvStudents.CurrentRow.Cells["Name"].Value.ToString();
                txtStudentCode.Text = dgvStudents.CurrentRow.Cells["Code"].Value.ToString();                
                ckbFinalYear.Checked = (bool)dgvStudents.CurrentRow.Cells["Term"].Value;
                //dtpBirthday.Value = (DateTime)dgvStudents.CurrentRow.Cells["DateOfBirth"].Value;
            }

            else
            {
                txtStudentName.Text = txtStudentCode.Text = string.Empty;
                ckbAllStudents.Checked = ckbFinalYear.Checked = false;
                dtpBirthday.Value = DateTime.Now;
            }
        }

        private void CboMajorsSelectedIndexChanged(object sender, EventArgs e)
        {
            LoadStudent();
        }

        private void DgvStudentsCurrentCellChanged(object sender, EventArgs e)
        {
            StudentCurrentRowChanged();
        }

        private void DgvStudentsCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvStudents == null ||
               dgvStudents.Columns[(string)typeof(Student).Properties().IsChecked] == null ||
               dgvStudents.Columns[(string)typeof(Student).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvStudents[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvStudents[e.ColumnIndex, e.RowIndex].Value;

            ckbAllStudents.Checked = DataGridViewHelper.AllRowsIsCheck(dgvStudents);
        }

        private void CkbAllStudentsCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvStudents, ckbAllStudents.Checked);
        }

        private void ReloadStudent(Student stundent)
        {
            LoadStudent();
            DataGridViewHelper.SetDgvCurrentCell(dgvStudents, stundent.Code);
            StudentCurrentRowChanged();
        }

        /// <summary>
        /// Event click button Add Student
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddStudentClick(object sender, EventArgs e)
        {
            try
            {
                var student = new Student{
                                       Name = txtStudentName.Text.Trim(),
                                       Code = txtStudentCode.Text.Trim(),
                                       IdMajor = (int) cboMajors.SelectedItem,
                                       DateOfBirth = dtpBirthday.Value,
                                       Term = ckbFinalYear.Checked };

                string message;

                if (_business.AddStudentValidator(student, out message))
                {
                    _business.AddStudent(student);

                    ReloadStudent(student);
                }
                else
                    MessageBox.Show(message);

            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click edit Major
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnEditStudentClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvStudents.CurrentRow != null)
                {
                    var student = new Student
                    {
                       Id = Convert.ToInt32(dgvStudents.CurrentRow.Cells[PropertiesConstants.Id].Value),
                       Name = txtStudentName.Text.Trim(),
                       Code = txtStudentCode.Text.Trim(),
                       DateOfBirth = dtpBirthday.Value,
                       Term = ckbFinalYear.Checked,
                    };
                    string message;
                    if (_business.EditStudentValidator(student, out message))
                    {
                        if (!_business.EditStudent(student))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.ProgramName);
                            return;
                        }
                        ReloadStudent(student);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click Delete Major
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteStudentClick(object sender, EventArgs e)
        {
            try
            {
                var students = new List<Student>();
                string message;

                for (var i = 0; i < dgvStudents.RowCount; i++)
                {
                    if (!(bool)dgvStudents[(string)typeof(Student).Properties().IsChecked, i].Value) continue;

                    students.Add(new Student
                    {
                        Id = (int)dgvStudents[(string)typeof(Student).Properties().Id, i].Value,
                        Name = dgvStudents[(string)typeof(Student).Properties().Name, i].Value.ToString(),
                        Code = dgvStudents["Code", i].Value.ToString(),
                        IdMajor = (int) cboMajors.SelectedItem,
                        DateOfBirth = (DateTime?) dgvStudents["DateOfBirth", i].Value,
                        Term = (bool) dgvStudents["Term", i].Value,
                        //Thesis = dgvStudents["Thesis", i].Value.ToString()
                    });
                }
                if (students.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                if (_business.DeleteStudentsValidator(students, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các sinh viên đã chọn"), FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteStudents(students);
                        ReloadStudent(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        #endregion

        private void ptbImportData_Click(object sender, EventArgs e)
        {
            //Import data
        }
    }
}
